package com.sx.zongzhi.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;

import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.SpinnerPubAdapter;
import com.sx.zongzhi.bean.GlobalBean;
import com.sx.zongzhi.bean.PopulationDetailBean;
import com.sx.zongzhi.bean.PublicBean;
import com.sx.zongzhi.presenter.CheckMessagePest;
import com.sx.zongzhi.presenter.PublicListPest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.ICheckMessageView;
import com.sx.zongzhi.view.IPublicBeanView;
import com.sx.zongzhi.widget.LoadDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by XZY on 2017/11/28.
 * 户籍信息添加或编辑
 */
public class HouseholdInforEditFragment extends Fragment implements IPublicBeanView,ICheckMessageView{

    @BindView(R.id.et_HomeID)
    EditText et_HomeID;
    @BindView(R.id.sp_Remark) Spinner sp_Remark;
    @BindView(R.id.sp_Relation) Spinner sp_Relation;
    private List<GlobalBean> relationList,remarkList;
    private CheckMessagePest messagePest;
    private PopulationDetailBean detailBean;
    private String orgId="";
    private String relationId="";
    private boolean isEdit;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_household_infor_edit,container,false);
        ButterKnife.bind(this,view);
        detailBean= (PopulationDetailBean) getArguments().getSerializable("PopulationDetailBean");
        isEdit=getArguments().getBoolean("isEdit");
        orgId=  getArguments().getString("orgId");
        showView();
        initData();
        return view;
    }

    public boolean submit(){
        String homeId=et_HomeID.getText().toString().trim();
        if (homeId.length()!=9){
            ToastUtils.showToast(getActivity(),"户号长度不正确");
            return false;
        }

        detailBean.setAccountNumber(homeId);
        GlobalBean relation=relationList.get(sp_Relation.getSelectedItemPosition());
        if (relation==null){
            ToastUtils.showToast(getActivity(),"请选择与户主关系");
            return false;
        }
        detailBean.setRelationShipWithHead(relation);
        GlobalBean remark=remarkList.get(sp_Remark.getSelectedItemPosition());
        if (remark==null){
            ToastUtils.showToast(getActivity(),"请选择人户标志");
            return false;
        }
        detailBean.setResidentStatus(remark);
        return true;
    }

    private void initData() {
        PublicListPest publicListPest=new PublicListPest(this);
        publicListPest.getPublicList("与户主关系");
        publicListPest.getPublicList("人户状态");
    }

    private void showView() {
        try {
            et_HomeID.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {}
                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length()==9&&et_HomeID.isEnabled()) {
                        checkMessage(s.toString());
                    }
                }
            });

            sp_Relation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    relationId=((GlobalBean)sp_Relation.getSelectedItem()).getId();
                    String homeId=et_HomeID.getText().toString().trim();
                    if (homeId.length()==9){
                        checkMessage(homeId);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {}
            });


            if (isEdit){
                et_HomeID.setClickable(false);
                et_HomeID.setEnabled(false);
                et_HomeID.setText(detailBean.getAccountNumber());
                relationId=detailBean.getRelationShipWithHead().getId();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 验证户号
     */
    private void checkMessage(String homeID) {
        if (messagePest == null) {
            messagePest = new CheckMessagePest(HouseholdInforEditFragment.this);
        }
        LoadDialog.show(getActivity(),"验证户号唯一性");
        messagePest.checkHouseHold("checkedFamilyIdCardNo.action",detailBean.getIdCardNo(),homeID,orgId,relationId);
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(getActivity());
        ToastUtils.showToast(getActivity(),message);
    }

    @Override
    public void getPublicList(PublicBean publicBean) {
        if ("与户主关系".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getRelationShipWithHead() != null) {
                id = detailBean.getRelationShipWithHead().getId();
            }
            relationList = publicBean.getDicts();
            showSpinner(sp_Relation, relationList,id);

        }
        if ("人户状态".equals(publicBean.getDomainName())) {
            String id = "";
            if (detailBean != null && detailBean.getResidentStatus() != null) {
                id = detailBean.getResidentStatus().getId();
            }
            remarkList = publicBean.getDicts();
            showSpinner(sp_Remark, remarkList,id);
        }
    }

    private void showSpinner(Spinner spinner, List<GlobalBean> datas,String id) {
        SpinnerPubAdapter adapter=new SpinnerPubAdapter(getActivity(),R.layout.item_text,datas);
        spinner.setAdapter(adapter);
        if (!BaseUtil.isEmpty(id)){
            int count=datas.size();
            for (int i=0;i<count;i++){
                if (id.equals(datas.get(i).getId())){
                    spinner.setSelection(i);
                    break;
                }
            }
        }

    }

    @Override
    public void checkSuccess(Boolean result, String message) {
        LoadDialog.dismiss(getActivity());
        if (!result){
            ToastUtils.showToast(getActivity(),message);
        }
    }
}
